package middleware

import (
	"fmt"
	"net/http"

	"gitee.com/go-course/go9/tree/master/projects/vblog/api/apps"
	"gitee.com/go-course/go9/tree/master/projects/vblog/api/apps/user"
	"github.com/gin-gonic/gin"
)

// 需要写一个Gin Auth中间件, 就是一个函数
// // HandlerFunc defines the handler used by gin middleware as return value.
// type HandlerFunc func(*Context)

// 函数写法
func AuthFunc(c *gin.Context) {
	fmt.Println(c.Request.Header)
	// 获取username, username 放到Cookie里面是比较常见
	// 从 cookie里面读取username, 通过username 判断该用户是否登录

	ck, err := c.Request.Cookie("username")
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"msg": err.Error()})
		c.Abort()
		return
	}
	username := ck.Value

	ck, err = c.Request.Cookie("session")
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"msg": err.Error()})
		c.Abort()
		return
	}
	session := ck.Value

	svc := apps.GetInternalApp(user.AppName).(user.Service)
	err = svc.CheckIsLogin(c.Request.Context(), user.NewCheckIsLogin(username, session))
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"msg": err.Error()})
		c.Abort()
		return
	}

	// flow 到后面的请求
	c.Next()
}
